package org.fastframework.boot.web.context;

import org.fastframework.boot.context.ApplicationContext;
import org.fastframework.boot.web.annotation.Controller;
import org.fastframework.boot.web.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WebApplicationContext {

    public static ConcurrentHashMap<String, Method> handlerMapping = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, Object> controllerMap = new ConcurrentHashMap<>();

    public WebApplicationContext() {
        init();
    }

    private static void init() {
        try {
            for (Map.Entry<Class<?>, Object> entry : ApplicationContext.beansFactory.entrySet()) {
                Class<?> clazz = entry.getKey();
                if (!clazz.isAnnotationPresent(Controller.class)) continue;
                //拼url时,是controller头的url拼上方法上的url
                String baseUrl = "";
                if (clazz.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping annotation = clazz.getAnnotation(RequestMapping.class);
                    baseUrl = annotation.value();
                }
                Method[] methods = clazz.getMethods();
                for (Method method : methods) {
                    if (!method.isAnnotationPresent(RequestMapping.class)) continue;
                    RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                    String url = annotation.value();
                    url = (baseUrl + "/" + url).replaceAll("/+", "/");
                    handlerMapping.put(url, method);
                    controllerMap.put(url, entry.getValue());
                    System.out.println(url + "," + method);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
